﻿#include <cassert>

#include "GraphicsTool/DatasPublic.h"


#include "GraphicsTool/NoLockPool.h"

COctreeFinder* COctreeFinder::mCOctreeFinder = nullptr;

COctreeFinder* COctreeFinder::Instance()
{
	if (!mCOctreeFinder)
	{
		mCOctreeFinder = new COctreeFinder();
	}

	return mCOctreeFinder;
}

COctreeFinder::COctreeFinder()
{
	mCOctreeSceneManager = new COctreeSceneManager();

	mIsUseThreadPools = false;

	mLockPool = nullptr;

}

COctreeFinder::~COctreeFinder()
{
	if (mCOctreeSceneManager)
	{
		delete mCOctreeSceneManager;
		mCOctreeSceneManager = nullptr;
	}

	if (mLockPool)
	{
		delete mLockPool;
		mLockPool = nullptr;
	}
}

void COctreeFinder::setIsUseThreadPools(bool isUseThreadPools)
{
	mIsUseThreadPools = isUseThreadPools;

	if (mIsUseThreadPools)
	{
		if (!mLockPool)
		{
			mLockPool = new  NoLockPool();
		}
		

		mLockPool->resetPool();

		mLockPool->init(10);

		for (size_t i = 0; i < mCOctreeSceneManager->mTotalNodes.size(); i++)
		{
			mLockPool->pushTask();
		}
	}
}

void COctreeFinder::addKongCaoIds(COctreeNode* node)
{
	//InteractorNode* node = new InteractorNode();
	//node->mids = ids;

	node->getWorldAABB();
	mCOctreeSceneManager->_updateOctreeNode(node);
}

void COctreeFinder::init(osg::BoundingBoxd &box, int depth)
{
	mCOctreeSceneManager->init(box, depth);
}

void COctreeFinder::resetOctree()
{
	mCollisionNode.clear();
	if (mCOctreeSceneManager)
	{
		delete mCOctreeSceneManager;
		mCOctreeSceneManager = new COctreeSceneManager();
	}
}

void COctreeFinder::calCollisionNode()
{
	if (mIsUseThreadPools)
	{
		mLockPool->mCOctreeSceneManager = mCOctreeSceneManager;
		mLockPool->mCollisionNode = &mCollisionNode;

		//加入任务
		for (size_t i = 0; i < mCOctreeSceneManager->mTotalNodes.size(); i++)
		{
			mLockPool->pushTask();
		}

		//开始启动
	}
	else
	{
		std::vector<COctreeNode*>& totalNodes = mCOctreeSceneManager->mTotalNodes;

		std::vector<COctreeNode*>::iterator it = totalNodes.begin();

		for (; it != totalNodes.end(); it++)
		{
			std::vector<COctreeNode*> desNodes;
			mCOctreeSceneManager->findNodes(mCOctreeSceneManager->mOctree, *it, *it, desNodes);

			if (desNodes.size())
			{
				mCollisionNode[*it] = desNodes;
			}
		}
	}

	//NoLockPool np;


	//for (size_t i = 0; i < 200; i++)
	//{
	//	std::function<int(int)> t = Test;
	//	np.pushTask(t);
	//}

	//pl.init(5);
}

